
import React,{Component} from 'react';
import DrawerLayout from './DrawerLayOut';
import PropTypes from "prop-types";

export default class Drawer extends Component {

    componentDidMount() {
        if (this.props.open) {
            this.drawer.openDrawer();
        }
    }

    componentDidUpdate(prevProps){
        if ( prevProps.open !== this.props.open ) {
            this.drawer[this.props.open ? 'openDrawer' : 'closeDrawer']();
        }
    }

    onOpenChange(isOpen) {
        if (this.props.onOpenChange) {
            this.props.onOpenChange(isOpen);
        }
    }

    render() {
        let { sidebar, position, drawerRef, ...restProps } = this.props;
        ['onOpenChange', 'onDrawerOpen', 'onDrawerClose', 'drawerPosition', 'renderNavigationView'].forEach(prop => {
            if (restProps.hasOwnProperty(prop)) {
                delete restProps[prop];
            }
        });
        let _position = DrawerLayout.positions.Left;
        if (position === 'right') {
            _position = DrawerLayout.positions.Right;
        }
        return (
            <DrawerLayout
                ref={(el) => {
                    if (drawerRef) {
                        drawerRef(el);
                    }
                    this.drawer = el;
                }}
                renderNavigationView={() => sidebar}
                drawerPosition={_position}
                onDrawerOpen={() => this.onOpenChange(true)}
                onDrawerClose={() => this.onOpenChange(false)}
                keyboardDismissMode="on-drag"
                {...restProps}
            />
        );
    }
}

Drawer.propTypes = {
    onOpenChange: PropTypes.func,
    open: PropTypes.bool,
    position: PropTypes.oneOf(['left', 'right' , 'top' , 'bottom']),
    drawerRef: PropTypes.func,
    drawerWidth: PropTypes.number,
    drawerBackgroundColor: PropTypes.string
}
Drawer.defaultProps = {
    position: 'left',
    open: false,
    drawerWidth: 260,
};